package com.itheima.java.ai.langchin4j.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.java.ai.langchin4j.entity.SymptomAssessment;
import com.itheima.java.ai.langchin4j.service.SymptomAssessmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 症状自评控制器
 *
 * @author xiaozhi
 * @since 2025-01-07
 */
@RestController
@RequestMapping("/api/symptom")
@RequiredArgsConstructor
@Tag(name = "症状自评管理", description = "症状自评相关接口")
public class SymptomAssessmentController {

    private static final Logger log = LoggerFactory.getLogger(SymptomAssessmentController.class);
    private final SymptomAssessmentService symptomAssessmentService;

    @PostMapping("/assessment")
    @Operation(summary = "创建症状评估", description = "用户提交症状信息进行AI分析评估")
    public ResponseEntity<Map<String, Object>> createAssessment(
            @RequestBody SymptomAssessment assessment,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // TODO: 从token中获取用户ID
            Long userId = 1L; // 临时硬编码，实际应从JWT token解析
            assessment.setUserId(userId);
            
            SymptomAssessment result = symptomAssessmentService.createAssessment(assessment);
            
            response.put("success", true);
            response.put("message", "症状评估创建成功");
            response.put("data", result);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("创建症状评估失败", e);
            response.put("success", false);
            response.put("message", "创建症状评估失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/assessments")
    @Operation(summary = "获取用户症状评估列表", description = "分页获取用户的症状评估记录")
    public ResponseEntity<Map<String, Object>> getAssessments(
            @RequestParam(name = "pageNum", defaultValue = "1") @Parameter(description = "页码") Integer pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") @Parameter(description = "页大小") Integer pageSize,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // TODO: 从token中获取用户ID
            Long userId = 1L;
            
            IPage<SymptomAssessment> page = symptomAssessmentService.getAssessmentsByUserId(userId, pageNum, pageSize);
            
            response.put("success", true);
            response.put("data", page);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取症状评估列表失败", e);
            response.put("success", false);
            response.put("message", "获取症状评估列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/assessment/{id}")
    @Operation(summary = "获取症状评估详情", description = "根据ID获取症状评估详细信息")
    public ResponseEntity<Map<String, Object>> getAssessmentById(
            @PathVariable @Parameter(description = "评估ID") Long id,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            SymptomAssessment assessment = symptomAssessmentService.getById(id);
            
            if (assessment == null) {
                response.put("success", false);
                response.put("message", "症状评估不存在");
                return ResponseEntity.notFound().build();
            }
            
            response.put("success", true);
            response.put("data", assessment);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取症状评估详情失败", e);
            response.put("success", false);
            response.put("message", "获取症状评估详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/recent")
    @Operation(summary = "获取最近的症状评估", description = "获取用户最近的症状评估记录")
    public ResponseEntity<Map<String, Object>> getRecentAssessments(
            @RequestParam(name = "limit", defaultValue = "5") @Parameter(description = "限制数量") Integer limit,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // TODO: 从token中获取用户ID
            Long userId = 1L;
            
            List<SymptomAssessment> assessments = symptomAssessmentService.getRecentAssessments(userId, limit);
            
            response.put("success", true);
            response.put("data", assessments);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取最近症状评估失败", e);
            response.put("success", false);
            response.put("message", "获取最近症状评估失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/analyze")
    @Operation(summary = "AI症状分析", description = "对症状进行AI分析，不保存评估记录")
    public ResponseEntity<Map<String, Object>> analyzeSymptoms(
            @RequestBody SymptomAssessment assessment) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String analysis = symptomAssessmentService.analyzeSymptoms(assessment);
            String riskLevel = symptomAssessmentService.calculateRiskLevel(assessment);
            String department = symptomAssessmentService.recommendDepartment(assessment.getMainSymptoms());
            
            Map<String, Object> result = new HashMap<>();
            result.put("analysis", analysis);
            result.put("riskLevel", riskLevel);
            result.put("recommendedDepartment", department);
            
            response.put("success", true);
            response.put("data", result);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("AI症状分析失败", e);
            response.put("success", false);
            response.put("message", "AI症状分析失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取症状评估统计", description = "获取用户的症状评估统计数据")
    public ResponseEntity<Map<String, Object>> getStatistics(
            @RequestParam(required = false) 
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) 
            @Parameter(description = "开始时间") LocalDateTime startTime,
            @RequestParam(required = false) 
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) 
            @Parameter(description = "结束时间") LocalDateTime endTime,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // TODO: 从token中获取用户ID
            Long userId = 1L;
            
            // 默认查询最近30天
            if (startTime == null) {
                startTime = LocalDateTime.now().minusDays(30);
            }
            if (endTime == null) {
                endTime = LocalDateTime.now();
            }
            
            Map<String, Object> statistics = symptomAssessmentService.getAssessmentStatistics(userId, startTime, endTime);
            
            response.put("success", true);
            response.put("data", statistics);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取症状评估统计失败", e);
            response.put("success", false);
            response.put("message", "获取症状评估统计失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/assessment/{id}/status")
    @Operation(summary = "更新评估状态", description = "更新症状评估的状态")
    public ResponseEntity<Map<String, Object>> updateAssessmentStatus(
            @PathVariable @Parameter(description = "评估ID") Long id,
            @RequestParam @Parameter(description = "新状态") String status,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Boolean success = symptomAssessmentService.updateAssessmentStatus(id, status);
            
            if (success) {
                response.put("success", true);
                response.put("message", "状态更新成功");
            } else {
                response.put("success", false);
                response.put("message", "状态更新失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("更新评估状态失败", e);
            response.put("success", false);
            response.put("message", "更新评估状态失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/assessment/{id}")
    @Operation(summary = "删除症状评估", description = "删除指定的症状评估记录")
    public ResponseEntity<Map<String, Object>> deleteAssessment(
            @PathVariable @Parameter(description = "评估ID") Long id,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // TODO: 从token中获取用户ID
            Long userId = 1L;
            
            Boolean success = symptomAssessmentService.deleteAssessment(id, userId);
            
            if (success) {
                response.put("success", true);
                response.put("message", "删除成功");
            } else {
                response.put("success", false);
                response.put("message", "删除失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("删除症状评估失败", e);
            response.put("success", false);
            response.put("message", "删除症状评估失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/pending-reviews")
    @Operation(summary = "获取待审核评估", description = "获取待医生审核的症状评估列表")
    public ResponseEntity<Map<String, Object>> getPendingReviews(
            @RequestParam(name = "pageNum", defaultValue = "1") @Parameter(description = "页码") Integer pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") @Parameter(description = "页大小") Integer pageSize,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            IPage<SymptomAssessment> page = symptomAssessmentService.getPendingReviews(pageNum, pageSize);
            
            response.put("success", true);
            response.put("data", page);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取待审核评估失败", e);
            response.put("success", false);
            response.put("message", "获取待审核评估失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/assessment/{id}/review")
    @Operation(summary = "医生审核评估", description = "医生对症状评估进行审核")
    public ResponseEntity<Map<String, Object>> reviewAssessment(
            @PathVariable @Parameter(description = "评估ID") Long id,
            @RequestParam @Parameter(description = "审核意见") String review,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // TODO: 从token中获取医生ID
            Long doctorId = 1L;
            
            Boolean success = symptomAssessmentService.reviewAssessment(id, doctorId, review);
            
            if (success) {
                response.put("success", true);
                response.put("message", "审核完成");
            } else {
                response.put("success", false);
                response.put("message", "审核失败");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("医生审核评估失败", e);
            response.put("success", false);
            response.put("message", "医生审核评估失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}